<template>
  <mu-container style="background: #fff;height: 100%;">
    <div class="load-container" v-if="showLoading">
      <dl style="text-align:center">
        <dt style="margin-bottom:0.1rem">
          <img style="width: .6rem;height: .6rem;" src="../../assets/img/logo.jpg" alt />
        </dt>
        <dd>
          <span
            style="
        font-size:0.18rem;
        font-weight:500;
        color:rgba(61,61,61,1);
        line-height:0.25rem;"
          >中国建筑</span>
        </dd>
      </dl>
    </div>
    <div class="login-container" v-else>
      <div
        class="ly_flex ly_flex_just_center ly_flex_col ly_flex_ali_center"
        style="padding: .42rem  0 .7rem "
      >
        <img style="width: .6rem;height: .6rem;" src="../../assets/img/logo.jpg" alt />
        <span
          style="
        font-size:0.18rem;
        font-weight:500;
        color:rgba(61,61,61,1);
        line-height:0.25rem;"
        >中国建筑</span>
      </div>
      <mu-form ref="form" :model="validateForm" class="mu-demo-form" style="padding:0 .49rem;">
        <mu-form-item prop="username" :rules="usernameRules" class="l-spaci-form">
          <mu-text-field
            v-model="validateForm.username"
            full-width
            placeholder="请输入账号"
            icon="account_circle"
            prop="username"
          ></mu-text-field>
        </mu-form-item>
        <mu-form-item prop="password" :rules="passwordRules" class="l-spaci-form">
          <mu-text-field
            v-model="validateForm.password"
            full-width
            icon="locked"
            placeholder="请输入密码"
            :action-icon="visibility ? 'visibility_off' : 'visibility'"
            :action-click="() => (visibility = !visibility)"
            :type="visibility ? 'text' : 'password'"
            prop="password"
          ></mu-text-field>
        </mu-form-item>
        <mu-form-item>
          <mu-button full-width color="primary" @click="submit">登 录</mu-button>
        </mu-form-item>
      </mu-form>
    </div>
  </mu-container>
</template>

<script>
export default {
  name: "successTips",
  data() {
    return {
      showLoading: true,
      api: {
        getWXAuthorizationApi: "/safety/getSignature",
        sshApi: ""
      },
      usernameRules: [
        { validate: val => !!val, message: "必须填写用户名" },
        { validate: val => val.length >= 3, message: "用户名长度大于3" }
      ],
      passwordRules: [
        { validate: val => !!val, message: "必须填写密码" },
        {
          validate: val => val.length >= 3 && val.length <= 10,
          message: "密码长度大于3小于10"
        }
      ],
      validateForm: {
        username: "",
        password: "",
        isAgree: false
      },
      visibility: false
    };
  },
  created() {
    this.getWXAuthorization();
    //this.textCode();
  },
  methods: {
    textCode() {
      let data = {
        corpId: "ww06e0eeb0e1c23079",
        ticket:
          "sM4AOVdWfPE4DxkXGEs8VDiUm72GMe3dRUx7QRD844Lbaw3IfTxJO5QKMqlzjvjOa9npodLLI4EK6b8FNTefhQ",
        signature: "bc97b97c50d5a7f1deaf3912e527b5e291ea9f86",
        noncestr: "v6mQPLWAjs01MXe8",
        timestamp: "1577519342",
        userInfo: {
          id: "155392",
          userName: "200A1475",
          employeeName: "赵男",
          fullName: "赵男",
          employeeNumber: "200A1475",
          sex: "男",
          position: null,
          mail: null,
          mobile: "15221499301",
          empId: null,
          ehrEmpId: null,
          isEmployee: null,
          tenantId: "166859688829256086",
          status: null,
          isDelete: "0",
          createdTime: "2018-02-07 00:05:46",
          createdUser: null,
          updatedTime: "2019-06-18 15:56:45",
          updatedUser: null,
          updatedUserName: null,
          orgName: "一个项目部",
          orgId: "159",
          orgType: "1",
          corpName: null,
          corpId: null,
          deptName: null,
          deptId: null,
          roleList: [
            {
              id: "166878119607666070",
              orgId: "102",
              orgName: null,
              roleCode: null,
              roleName: "管理员",
              roleDesc: "111111",
              roleStatus: "1",
              tenantId: "166859688829256086",
              isDelete: "0",
              createdTime: "2019-12-04 19:29:20",
              createdUser: "131671",
              updatedTime: "2019-12-04 19:29:20",
              updatedUser: "110405",
              members: null,
              type: null
            }
          ],
          userType: "1"
        }
      };
      this.setSession(data.userInfo);
      wx.config({
        beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: data.corpId, // 必填，企业微信的corpID
        timestamp: data.timestamp, // 必填，生成签名的时间戳
        nonceStr: data.noncestr, // 必填，生成签名的随机串
        signature: data.signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
        jsApiList: ["chooseImage", "invoke"] // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
      });
      wx.ready(function() {
        wx.checkJsApi({
          jsApiList: ["invoke", "scanQRCode"], // 需要检测的JS接口列表，所有JS接口列表见附录2,
          success: function(ress) {
            // 以键值对的形式返回，可用的api值true，不可用为false
            // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
          }
        });
        // wx.scanQRCode({
        //   desc: 'scanQRCode desc',
        //   needResult: 0, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
        //   scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是条形码（一维码），默认二者都有
        //   success: function (res) {
        //     // 回调
        //   },
        //   error: function (res) {
        //     if (res.errMsg.indexOf('function_not_exist') > 0) {
        //       alert('版本过低请升级')
        //     }
        //   }
        // });
      });
      wx.error(function(res) {
        console.log("错误：" + JSON.stringify(res));
      });
    },
    getWXAuthorization() {
      this.showLoading = true;
      let code = "";
      code = Util.getQueryString("code");
      let url = location.href.split("#")[0];
      this.$A
        .Go("GET", this.api.getWXAuthorizationApi, { url: url, code: code })
        .then(response => {
          if (response.code == 200) {
            let data = response.body;
            if (data.userInfo) {
              this.setSession(data.userInfo);
            } else {
              this.showLoading = false;
            }
            wx.config({
              beta: true, // 必须这么写，否则wx.invoke调用形式的jsapi会有问题
              debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              appId: data.corpId, // 必填，企业微信的corpID
              timestamp: data.timestamp, // 必填，生成签名的时间戳
              nonceStr: data.noncestr, // 必填，生成签名的随机串
              signature: data.signature, // 必填，签名，见 附录-JS-SDK使用权限签名算法
              jsApiList: ["chooseImage", "invoke"] // 必填，需要使用的JS接口列表，凡是要调用的接口都需要传进来
            });
            wx.ready(function() {
              wx.checkJsApi({
                jsApiList: ["invoke", "scanQRCode"], // 需要检测的JS接口列表，所有JS接口列表见附录2,
                success: function(ress) {
                  // 以键值对的形式返回，可用的api值true，不可用为false
                  // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                  sessionStorage.setItem("wx",true)
                }
              });
              // wx.scanQRCode({
              //   desc: 'scanQRCode desc',
              //   needResult: 0, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
              //   scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是条形码（一维码），默认二者都有
              //   success: function (res) {
              //     // 回调
              //   },
              //   error: function (res) {
              //     if (res.errMsg.indexOf('function_not_exist') > 0) {
              //       alert('版本过低请升级')
              //     }
              //   }
              // });
            });
            wx.error(function(res) {
              console.log("错误：" + JSON.stringify(res));
            });
          } else {
            this.showLoading = false;
          }
        })
        .catch(err => {
          console.log("ERR:" + err);
          this.showLoading = false;
        });
    },
    submit() {
      this.$refs.form.validate().then(result => {
        console.log("form valid: ", result);
        if (result) {
          this.goLogin(this.validateForm);
        }
      });
    },
    clear() {
      this.$refs.form.clear();
      this.validateForm = {
        username: "",
        password: "",
        isAgree: false
      };
    },
    async goLogin(values) {
      this.$A.Go("GET", "/safety/login", { appUserName: values.username , clientType:'1'}).then(
        async success => {
          if (success.code == 200) {
            this.$A.MS("登录成功", "success");
            let data = success.body;
            this.setSession(data);
          } else {
            this.$A.MS(success.msg);
          }
        },
        function(err) {
          console.log(err);
        }
      );
    },
    async setSession(data) {
      this.$A.SS("userInfo", {
        corpId: data.corpId,
        corpName: data.corpName,
        employeeNumber: data.employeeNumber,
        employeeName: data.employeeName,
        userId: data.id,
        userName: data.fullName,
        userNumber: data.userName,
        mobile: data.mobile,
        roleList: data.roleList,
        id: data.id,
        orgId: data.orgId,
        type: data.orgType,
        orgName: data.orgName,
        tenantId: data.tenantId,
        userType: data.userType,
        token:data.token,
      });

      
      this.$A.SS("orgInfo", {orgId:data.chOrgId,orgName:data.chOrgName,type:data.chOrgType});
      await this.getList(data);
      
      this.$router.push("/mainMenu");
    },
    //全集菜单
    async getList(list) {
      // alert(1)
      let _this = this;
      let obj = {
        // pageNo:-1,
        // pageSize:0,
        obj: {
          userId: list.id,
          type: "",
          clientType: ["2", "3"],
          directType: list.orgType == 1 ? ["2", "3"] : ["1", "3"] //如果是项目层级的，就显示项目和全部的，反之组织和全部的
        }
      };
      return this.$A.Go("post", "/safety/resource/user", obj).then(
        function(success) {
          if (success.code == 200) {
            let data = JSON.parse(JSON.stringify(success.body));
            // 首先做排序动作

            // _this.parentTree = data
            let treeTest = _this.getRouterFn(success.body);
            _this.$A.SS("P", treeTest);
          } else {
            _this.$A.MS(success.msg);
          }
          return;
        },
        function(err) {
          console.log(err);
        }
      );
    },
    getRouterFn(tree = []) {
      let arr = [];
      for (let i = tree.length; i--; ) {
        tree[i]["router"] && arr.push(tree[i]["router"]);
        if (tree[i]["children"] && tree[i]["children"].length > 0) {
          arr.push(...this.getRouterFn(tree[i]["children"]));
        }
      }
      return arr;
    }
  }
};
</script>
<style lang="scss" scoped>
.load-container {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.body {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 2rem;
  width: 100%;
  .lan-success-tips-icon {
    font-size: 0.75rem;
    color: #24d90c;
    line-height: 0.75rem;
    margin-bottom: 0.18rem;
    margin-top: 0.33rem;
  }
  .lan-success-tips-text {
    font-size: 0.19rem;
    font-weight: 500;
    color: #3d3d3d;
  }
}
.mu-demo-form {
  >>> .mu-text-field-input {
    padding-left: 0.5rem;
  }
}
</style>
<style lang="scss">
  .l-spaci-form{
    >.mu-form-item-content{
      >.mu-input{
        >.mu-input-icon{
          left: 4px;
          top: 3px;
        }
        >.mu-input-content{
          >.mu-text-field-input{
            padding-left:30px;
          }
        }
      }
    }
  }
</style>
